<?php

/**
 * @Author: Maowenfu
 * @Date:   2020-11-19 16:59:06
 * @Last Modified by:   Mr.Mao
 * @Last Modified time: 2021-07-30 16:51:31
/*------------------------------------------------------ */
//-- 转赠相关
//-- Author: iqgmy
/*------------------------------------------------------ */
namespace app\member\controller\api;
use app\ApiController;
use app\member\model\TransferLogModel;
use app\member\model\AccountModel;
use app\member\model\UsersModel;
use think\Db;
class Transfer  extends ApiController{
    /*------------------------------------------------------ */
    //-- 优先执行
    /*------------------------------------------------------ */
    public function initialize()
    {
        parent::initialize();
        $this->Model = new TransferLogModel();
    }
    /**
     * [getToUserInfo 获取收款用户]
     * @return [type] [description]
     */
    public function getToUserInfo()
    {
        $user_id = input('user_id','','trim');
        if (empty($user_id)) return $this->error('传参错误.');
        $userInfo = (new UsersModel)->where('user_id',$user_id)->find();
        if (empty($userInfo)) return $this->error('用户不存在.');
        if ($userInfo['user_id'] == $this->userInfo['user_id']) return $this->error('不能转赠给自己.');
        $UsersBindSuperiorModel = new \app\member\model\UsersBindSuperiorModel();
        $where = [];
        $where[] = ['user_id','=',$userInfo['user_id']];
        $where[] = ['','exp',Db::raw("FIND_IN_SET('".$this->userInfo['user_id']."',superior)")];
        $nexCount = $UsersBindSuperiorModel->where($where)->count();
        unset($where);
        $where = [];
        $where[] = ['user_id','=',$this->userInfo['user_id']];
        $where[] = ['','exp',Db::raw("FIND_IN_SET('".$userInfo['user_id']."',superior)")];
        $preCount = $UsersBindSuperiorModel->where($where)->count();

        if ($nexCount <= 0 && $preCount <= 0) {
            //return $this->error('该用户与您不在同一关系链上.');
        }

        $data['toUserInfo'] = $userInfo->toArray();
        return $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 提交转赠
    /*------------------------------------------------------ */
    public function post()
    {
    	$money = input('money') * 1;
        $type = input('type');
        if(empty(strstr('balance,integral',$type))){
            return $this->error('转赠类型错误.');
        }
        $type=$type.'_money';
        if ($money <= 0){
            return $this->error('请输入转赠金额.');
        }
        if ($this->userInfo['account'][$type] - $money < 0) {
        	return $this->error('积分不足.');
        }
        $to_user = input('to_user',0,'intval');
        if ($to_user <= 0) $this->error('请输入收款用户.');
        $UsersModel = new UsersModel();
        $toUserInfo = $UsersModel->find($to_user);

        if (empty($toUserInfo) == true) return $this->error('用户不存在.');
        if ($toUserInfo['user_id'] == $this->userInfo['user_id']) {
            return $this->error('不能转赠给自己');
        }

        // $UsersBindSuperiorModel = new \app\member\model\UsersBindSuperiorModel();
        // $superior = $UsersBindSuperiorModel->where('user_id',$this->userInfo['user_id'])->value('superior');
        // $superiorArr = explode(',',$superior);

        // $where = [];
        // $where[] = ['user_id','=',$toUserInfo['user_id']];
        // $where[] = ['','exp',Db::raw("FIND_IN_SET('".$this->userInfo['user_id']."',superior)")];
        // $count = (new \app\member\model\UsersBindSuperiorModel())->where($where)->count();
        // if ($count <= 0) {
        //     return $this->error('该用户不是您的下级.');
        // }

        $UsersBindSuperiorModel = new \app\member\model\UsersBindSuperiorModel();
        $where = [];
        $where[] = ['user_id','=',$toUserInfo['user_id']];
        $where[] = ['','exp',Db::raw("FIND_IN_SET('".$this->userInfo['user_id']."',superior)")];
        $nexCount = $UsersBindSuperiorModel->where($where)->count();
        unset($where);
        $where = [];
        $where[] = ['user_id','=',$this->userInfo['user_id']];
        $where[] = ['','exp',Db::raw("FIND_IN_SET('".$toUserInfo['user_id']."',superior)")];
        $preCount = $UsersBindSuperiorModel->where($where)->count();

        if ($nexCount <= 0 && $preCount <= 0) {
            //return $this->error('该用户与您不在同一关系链上.');
        }
        unset($where);
        unset($where);
        // $superiorArr

        $remarks = input('remarks','','trim');
        if ($remarks == '') {
        	return $this->error('请填写转赠备注.');
        }
        $time = time();
        $inArr['money'] = $money;
        $inArr['remarks'] = $remarks;
        $inArr['form_user'] = $this->userInfo['user_id'];
        $inArr['to_user'] = $toUserInfo['user_id'];
        $inArr['add_time'] = $time;

        Db::startTrans();
        $res = $this->Model->save($inArr);
        $log_id = $this->Model->log_id;
        if ($res < 1) {
            Db::rollback();
            return $this->error('转赠失败.');
        }
        $AccountModel = new AccountModel();
        $changedata = [];
        $changedata['change_desc'] = '转赠给用户'.$inArr['to_user'].'扣除';
        $changedata['change_type'] = 20;
        $changedata['by_id'] = $log_id;
        $changedata['is_transfer'] = 1;
        $changedata[$type] = $inArr['money'] * -1;

        $res = $AccountModel->change($changedata, $inArr['form_user'], false);
        if ($res !== true) {
            Db::rollback();// 回滚事务
            return $this->error('转赠扣除用户积分失败.');
        }
        unset($changedata);
        $changedata = [];
        $changedata['change_desc'] = '用户：'.$inArr['form_user'].'转赠转入';
        $changedata['change_type'] = 21;
        $changedata['is_transfer'] = 1;
        $changedata['by_id'] = $log_id;
        $changedata[$type] = $inArr['money'] * 1;
        $res = $AccountModel->change($changedata, $inArr['to_user'], false);
        if ($res !== true) {
            Db::rollback();// 回滚事务
            return $this->error('转赠转入用户积分失败.');
        }
        unset($changedata);
        Db::commit();
        return $this->success('转赠成功.');
    }
    /**
     * [upTransfer 升级转账]
     */
    public function upTransfer()
    {
        $id = input('id',0,'intval');
        if ($id <= 0) return $this->error('传参错误.');
        $UsersTaskModel = new \app\member\model\UsersTaskModel();
        $taskInfo = $UsersTaskModel->find($id);
        if (empty($taskInfo)) return $this->error('数据不存在.');
        $UsersModel = new UsersModel();
        $toUserInfo = $UsersModel->info($taskInfo['touid']);
        if (empty($toUserInfo)) return $this->error('收款用户不存在.');
        $money = $taskInfo['num'] * 1;
        if ($this->userInfo['account']['balance_money'] - $money < 0) {
            return $this->error('积分不足.');
        }
        $remarks = '升级转账，下级升级身份需要给指定上级转账'.$money;
        $time = time();
        $inArr['money'] = $money;
        $inArr['remarks'] = $remarks;
        $inArr['form_user'] = $this->userInfo['user_id'];
        $inArr['to_user'] = $toUserInfo['user_id'];
        $inArr['add_time'] = $time;
        Db::startTrans();
        $res = $this->Model->save($inArr);
        $log_id = $this->Model->log_id;
        if ($res < 1) {
            Db::rollback();
            return $this->error('转账失败.');
        }
        $AccountModel = new AccountModel();
        $changedata = [];
        $changedata['change_desc'] = '升级身份，转账给用户'.$inArr['to_user'].'扣除';
        $changedata['change_type'] = 20;
        $changedata['by_id'] = $log_id;
        $changedata['balance_money'] = $inArr['money'] * -1;
        $res = $AccountModel->change($changedata, $inArr['form_user'], false);
        if ($res !== true) {
            Db::rollback();// 回滚事务
            return $this->error('转账扣除用户积分失败.');
        }
        unset($changedata);
        $changedata = [];
        $changedata['change_desc'] = '下级升级身份，用户：'.$inArr['form_user'].'转账转入';
        $changedata['change_type'] = 21;
        $changedata['by_id'] = $log_id;
        $changedata['balance_money'] = $inArr['money'] * 1;
        $res = $AccountModel->change($changedata, $inArr['to_user'], false);
        if ($res !== true) {
            Db::rollback();// 回滚事务
            return $this->error('转账转入用户积分失败.');
        }
        unset($changedata);
        $res = $UsersTaskModel->where('id',$id)->update(['status'=>1]);
        if ($res < 1) {
            Db::rollback();// 回滚事务
            return $this->error('升级处理失败.');
        }

         // $account = $AccountModel->where('user_id', $inArr['form_user'])->find();
         // print_r($account);

        // 判断是否已完成所有任务，完成即升级
        $taskList = (new \app\member\model\UsersTaskModel)->where([['user_id','=',$this->userInfo['user_id']],['up_role','=',$this->userInfo['up_role']],['role_id','=',$this->userInfo['role_id']]])->select()->toArray();
        if (empty($taskList)) {
            Db::rollback();// 回滚事务
            return $this->error('升级处理失败.');
        }

        $is_up = true;
        foreach ($taskList as $value) {
            if ($value['status'] == 0) {
                $is_up = false;
            }
        } 
        if ($is_up == true) {
            $upData = [];
            $upData['up_role'] = 0;
            $upData['role_id'] = $this->userInfo['up_role'];
            $upData['last_up_role_time'] = time();
            $res = $UsersModel->upInfo($this->userInfo['user_id'], $upData);
            if ($res < 1) {
                return false;
            }
            $LogSysModel = new \app\member\model\LogSysModel();
            $roleList = (new \app\distribution\model\DividendRoleModel)->getRows();
            $inData['edit_id'] = $this->userInfo['user_id'];
            $inData['log_info'] = '';
            $inData['log_info'] = '完成升级任务，';
            $inData['log_info'] .= '【' . ($this->userInfo['role_id'] == 0 ? '粉丝' : $roleList[$this->userInfo['role_id']]['role_name']) . '】升级为【' . $roleList[$upData['role_id']]['role_name'] . '】';
            $inData['module'] = request()->path();
            $inData['log_ip'] = request()->ip();
            $inData['log_time'] = time();
            $inData['user_id'] = 0;
            $LogSysModel->create($inData);

            $UsersModel->cleanMemcache($this->userInfo['user_id']);

            $res = $UsersModel->judgeUpgrade($this->userInfo['user_id']);
            if (true !== $res) {
                Db::rollback();// 回滚事务
                return $this->error('升级失败.',0);
            }

            Db::commit();
            $userInfo = $UsersModel->info($this->userInfo['user_id']);
            if ($userInfo['up_role'] > 0) {
                return $this->success('升级成功，您还可以升级至更高级别.');
            }else{
                return $this->success('升级成功.');
            }
            
        }

        Db::commit();
        return $this->success('转账成功.');
    }
}